package com.hairline.type_handler;


import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(String[].class) //javabean中成员变量类型
@MappedJdbcTypes(JdbcType.VARCHAR) //表中某列的类型
public class VarcharToStringArray implements TypeHandler<String[]>{
       private   ObjectMapper objectMapper=new ObjectMapper();
//输入映射
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, String[] strings, JdbcType jdbcType) throws SQLException {

//        StringBuffer sb=new StringBuffer();
//        for (String string : strings) {
//            sb.append(string);
//        }
//        String param = sb.toString();
//
//        if(StringUtil.isEmpty(param)){
//            param="[]";
//        }
//        preparedStatement.setString(index,param);
        String param = objectMapper.writeValueAsString(strings);
        preparedStatement.setString(index,param);
    }
//输出映射
    @SneakyThrows
    @Override
    public String[] getResult(ResultSet resultSet, String column) throws SQLException {
        String string = resultSet.getString(column);
        String[] strings = objectMapper.readValue(string, String[].class);

        return strings;
    }
//存储过程
    @SneakyThrows
    @Override
    public String[] getResult(ResultSet resultSet, int index) throws SQLException {
        String string = resultSet.getString(index);
        String[] strings = objectMapper.readValue(string, String[].class);
        return new String[0];
    }
//回调函数
    @SneakyThrows
    @Override
    public String[] getResult(CallableStatement callableStatement, int index) throws SQLException {
        String string = callableStatement.getString(index);
        String[] strings = objectMapper.readValue(string, String[].class);
        return strings;
    }

}
